#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <readline/readline.h>
#include <readline/history.h>

#include "rm.h"

void cmd_rm(char *comm)
{
	char *argv[4];
	int nr=0, ch, i=0, ok_i=0, ok_R=0, ok_v=0;
	argv[i] = strtok (comm, " ");
	nr++; i++;
	while ((argv[i++] = strtok (NULL, " -")) != NULL)
		nr++;
	if (nr < 2)
	{
		fprintf (stderr, "invalid command!\n");
		fprintf (stderr, "usage: rm file\n");
	}
	else {
		int i = 1;
		while (i < nr)
		{
			if (strcmp (argv[i], "i") == 0)	
				ok_i = 1;
			else if (strcmp (argv[i], "R") == 0)
				ok_R = 1;
			else if (strcmp (argv[i], "v") == 0)
				ok_v = 1;
			i++;
		}
		i = 1;
		if (ok_i == 1)
			i++;
		if (ok_R == 1)
			i++;
		if (ok_v == 1)
			i++;
		while (i < nr)
		{
			if (access (argv[i], F_OK) == 0)
			{
				struct stat stat_buf;
				if (stat (argv[i], &stat_buf) == 0)
					if (S_ISREG (stat_buf.st_mode)) // a file
						unlink (argv[i]);
					else if (S_ISDIR (stat_buf.st_mode) && ok_R == 1) // a folder
					{
						DIR *nume = opendir (argv[i]);
						struct dirent *x;
						while ((x = readdir(nume)) != NULL) {
							fprintf (stderr, "%s\n",x->d_name);
							unlink (x->d_name); }
						closedir (nume);
						unlink (argv[i]);
					}
			}
			else
				fprintf (stderr, "file `%s' not found\n", argv[i]);
			if (ok_v == 1)
				fprintf (stdout, "removed `%s'\n", argv[i]);
			i++;
		}
	}
}

int main()
{
	char *comm = readline ("usage: rm file\ncommand: ");
	cmd_rm(comm);
	return 0;
}
